package com.jch.sc.server;

import com.alibaba.fastjson.JSON;
import com.jch.sc.msg.Request;
import com.jch.sc.msg.Response;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Request request = (Request) msg;
        System.out.println("Request INFO: " + JSON.toJSONString(request));

        Response response = new Response();
        response.setRequestId(request.getRequestId());
        response.setParam(request.getResult() + " 请求成功！ 服务器反馈信息。");

        ctx.writeAndFlush(response);
        // 释放 请求对象
        ReferenceCountUtil.release(request);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
